package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.cache.J2CacheUtils;
import com.sugon.dao.DevMainBaseDao;
import com.sugon.dao.DevTypeDao;
import com.sugon.dao.DeviceInfoDao;
import com.sugon.dao.FactoryTypeDao;
import com.sugon.entity.DevMainBaseEntity;
import com.sugon.entity.DevTypeEntity;
import com.sugon.entity.FactoryTypeEntity;
import com.sugon.service.DevMainBaseService;
import com.sugon.service.DeviceInfoService;
import com.sugon.utils.Constant;
import com.sugon.utils.ShiroUtils;
import com.sugon.utils.StringUtils;
import com.sugon.utils.excel.ExcelImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

import static com.sugon.utils.ShiroUtils.getUserId;

/**
 * 维护库Service实现类
 *
 * @author sugon
 * @date 2019-07-16 14:46:43
 */
@Service("devMainBaseService")
public class DevMainBaseServiceImpl implements DevMainBaseService {
    @Autowired
    private DevMainBaseDao devMainBaseDao;
    @Autowired
    private DevTypeDao devTypeDao;
    @Autowired
    private DeviceInfoDao deviceInfoDao;
    @Autowired
    private FactoryTypeDao factoryTypeDao;
    @Resource
    private DeviceInfoService deviceInfoService;

    /**
     * queryObject
     *
     * @param id 主键
     * @return
     */
    @Override
    public DevMainBaseEntity queryObject(String id) {
        return devMainBaseDao.queryObject(id);
    }

    /**
     * queryList
     *
     * @param map 参数
     * @return
     */
    @Override
    public List<DevMainBaseEntity> queryList(Map<String, Object> map) {
        return devMainBaseDao.queryList(map);
    }

    /**
     * queryTotal
     *
     * @param map 参数
     * @return
     */
    @Override
    public int queryTotal(Map<String, Object> map) {
        return devMainBaseDao.queryTotal(map);
    }

    /**
     * queryAllList
     *
     * @param map
     * @return
     */
    @Override
    public List<DevMainBaseEntity> queryAllList(Map<String, Object> map) {
        return devMainBaseDao.queryAllList(map);
    }

    /**
     * queryAllByDevTotal
     *
     * @param map
     * @return
     */
    @Override
    public int queryAllByDevTotal(Map<String, Object> map) {
        return devMainBaseDao.queryAllByDevTotal(map);
    }

    /**
     * queryAllByDevList
     *
     * @param map
     * @return
     */
    @Override
    public List<DevMainBaseEntity> queryAllByDevList(Map<String, Object> map) {
        return devMainBaseDao.queryAllByDevList(map);
    }

    /**
     * 预测性
     *
     * @param file
     * @return
     */
    @Override
    public int importPDM(MultipartFile file) {
        //获取所有表格数据
        List<String[]> list = ExcelImport.getExcelData(file);
        int count = 0;
        if (CollectionUtil.isNotEmpty(list)) {
            for (int i = 1; i < list.size(); i++) {
                DevMainBaseEntity dmb = new DevMainBaseEntity();
                dmb.setId(RandomUtil.randomString(32));
                dmb.setCreateDate(new Date());
                dmb.setCreateUser(ShiroUtils.getUserId());
                dmb.setMainType(1);
                dmb.setLockFlag(1);
                String[] array1 = list.get(i);
                String[] array = new String[array1.length];
                System.arraycopy(array1, 0, array, 0, array1.length);
                //选项编码
                if (StringUtils.isNotEmpty(array[0])) {
                    String code = array[0];
                    dmb.setCode(code);
                } else {
                    String code = J2CacheUtils.getSequenceNoDate(4, "PDM");
                    dmb.setCode(code);
                }
                //选项名称
                if (StringUtils.isNotEmpty(array[1])) {
                    dmb.setName(array[1]);
                } else {
                    continue;
                }
                //设备类型
                if (StringUtils.isNotEmpty(array[2])) {
                    dmb.setDevType(array[2]);
                    DevTypeEntity dt = devTypeDao.queryObjectByCode(array[2]);
                    dmb.setDevTypeName(dt.getTypeName());
                } else {
                    continue;
                }

                //设备供应商
                if (StringUtils.isNotEmpty(array[3])) {
                    String supply = array[3];
                    List<FactoryTypeEntity> lists = factoryTypeDao.queryObjectByName(supply, 0);
                    FactoryTypeEntity ft = lists.get(0);
                    String code = ft.getFaCode();
                    dmb.setDevSupply(code);
                    dmb.setDevSupplyName(ft.getFaName());
                } else {
                    continue;
                }
                //检查标准 内容 公用
                if (StringUtils.isNotEmpty(array[4])) {
                    dmb.setCheckSt(array[4]);
                } else {
                    continue;
                }
                //测量方法
                if (StringUtils.isNotEmpty(array[5])) {
                    dmb.setMethodType(array[5]);
                    dmb.setRemark(array[5]);
                } else {
                    continue;
                }
                //检测工具
                if (StringUtils.isNotEmpty(array[6])) {
                    dmb.setCheckTool(array[6]);
                } else {
                    continue;
                }
                //属性
                if (StringUtils.isNotEmpty(array[7])) {
                    int arr;
                    switch (array[7]) {
                        case "E":
                            arr = 2;
                            break;
                        case "S":
                            arr = 3;
                            break;
                        default:
                            // 其它情况默认为1
                            arr = 1;
                    }
                    dmb.setAttribute(arr);
                } else {
                    continue;
                }
                //设备状态
                if (StringUtils.isNotEmpty(array[8])) {
                    dmb.setDevStatus(Integer.parseInt(array[8]));
                } else {
                    continue;
                }
                //选项备注
                if (StringUtils.isNotEmpty(array[9])) {
                    dmb.setRemark(array[9]);
                }
                //人次
                if (StringUtils.isNotEmpty(array[10])) {
                    dmb.setPerEv(Integer.parseInt(array[10]));
                } else {
                    continue;
                }
                //生产时间
                if (StringUtils.isNotEmpty(array[11])) {
                    dmb.setCheckDateUprud(Integer.parseInt(array[11]));
                }
                //非生产时间
                if (StringUtils.isNotEmpty(array[12])) {
                    dmb.setCheckDatePrud(Integer.parseInt(array[12]));
                }
                //实施频率
                if (StringUtils.isNotEmpty(array[13])) {
                    dmb.setFreRate(Integer.parseInt(array[13]));
                } else {
                    continue;
                }
                devMainBaseDao.save(dmb);
                count++;
            }
        }
        return count;
    }

    /**
     * 预防性
     * importPM
     *
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int importPM(MultipartFile file) {
        //获取所有表格数据
        List<String[]> list = ExcelImport.getExcelData(file);
        int count = 0;
        for (int i = 1; i < list.size(); i++) {
            DevMainBaseEntity dmb = null;
            boolean isSave = true;
            String[] array1 = list.get(i);
            String[] array = new String[14];
            System.arraycopy(array1, 0, array, 0, array1.length);
            // 根据选项编码是否填写确定逻辑
            String newDcode = array[0];
            if (StrUtil.isNotEmpty(newDcode)) {
                dmb = devMainBaseDao.getByDcode(newDcode);
                if (dmb != null) {
                    isSave = false;
                }
            }
            if (dmb == null) {
                dmb = new DevMainBaseEntity();
            }
            //选项名称
            if (StringUtils.isNotEmpty(array[1])) {
                dmb.setName(array[1]);
            }
            //设备类型
            if (StringUtils.isNotEmpty(array[2])) {
                String type = StrUtil.trim(array[2]);
                DevTypeEntity dt = devTypeDao.queryObjectByDCODE(type);
                if (dt == null) {
                    continue;
                }
                // 只能关联设备小类
                if (!NumberUtil.equals(dt.getTypeTp(), 0)) {
                    continue;
                }
                dmb.setDevType(type);
                dmb.setDevTypeName(dt.getTypeName());
            }
            //设备供应商
            if (StringUtils.isNotEmpty(array[3])) {
                String supply = StrUtil.trim(array[3]);
                List<FactoryTypeEntity> lists = factoryTypeDao.queryObjectByName(supply, 0);
                if (CollectionUtil.isEmpty(lists)) {
                    continue;
                }
                FactoryTypeEntity ft = lists.get(0);
                String code = ft.getFaCode();
                dmb.setDevSupply(code);
            }
            // 维护内容
            if (StringUtils.isNotEmpty(array[4])) {
                dmb.setCheckContent(StrUtil.trim(array[4]));
            }

            //维护标准
            if (StringUtils.isNotEmpty(array[5])) {
                dmb.setCheckSt(StrUtil.trim(array[5]));
            }
            //属性
            if (StringUtils.isNotEmpty(array[6])) {
                int arr = 1;
                switch (array[6]) {
                    case "C":
                        arr = 1;
                        break;
                    case "E":
                        arr = 2;
                        break;
                    case "S":
                        arr = 3;
                }
                dmb.setAttribute(arr);
            }
            // 物料需求
            if (StringUtils.isNotEmpty(array[7])) {
                dmb.setMaterialRequ(StrUtil.trim(array[7]));
            }

            // 方法及工具
            if (StringUtils.isNotEmpty(array[8])) {
                dmb.setMethodType(StrUtil.trim(array[8]));
            }
            // 备注
            if (StringUtils.isNotEmpty(array[9])) {
                dmb.setRemark(array[9]);
            }
            //人次
            if (StringUtils.isNotEmpty(array[10])) {
                dmb.setPerEv(Integer.parseInt(array[10]));
            }
            //生产时间
            if (StringUtils.isNotEmpty(array[11])) {
                dmb.setCheckDatePrud(Integer.parseInt(array[11]));
                dmb.setDevStatus(1);
            }
            //非生产时间
            if (StringUtils.isNotEmpty(array[12])) {
                dmb.setCheckDateUprud(Integer.parseInt(array[12]));
                dmb.setDevStatus(0);
            }
            //实施频率
            if (StringUtils.isNotEmpty(array[13])) {
                dmb.setFreRate(Integer.parseInt(array[13]));
            }
            dmb.setMainType(2);
            if (isSave) {
                save(dmb);
            } else {
                update(dmb);
            }
            count++;
        }

        return count;
    }

    /**
     * queryAllTotal
     *
     * @param map
     * @return
     */
    @Override
    public int queryAllTotal(Map<String, Object> map) {
        return devMainBaseDao.queryAllTotal(map);
    }

    /**
     * getBySupplyAndType
     *
     * @param devSupply 设备供应商编码
     * @param devType   设备小类别编码
     * @param mainType  预防性还是预测性
     * @return
     */
    @Override
    public List<DevMainBaseEntity> getBySupplyAndType(String devSupply, String devType, Integer mainType) {
        Map<String, Object> params = new HashMap<>();
        params.put("devSupply", devSupply);
        params.put("devType", devType);
        params.put("mainType", mainType);
        return devMainBaseDao.queryAllList(params);
    }

    /**
     * save
     *
     * @param devMainBase 实体
     * @return
     */
    @Override
    public int save(DevMainBaseEntity devMainBase) {
        String baseId = RandomUtil.randomString(32);
        devMainBase.setId(baseId);
        devMainBase.setCreateUser(getUserId());
        devMainBase.setCreateDate(DateUtil.date());
        devMainBase.setUpdateDate(devMainBase.getCreateDate());
        devMainBase.setUpdateUser(devMainBase.getCreateUser());
        devMainBase.setLockFlag(1);
        devMainBase.setDelFlag(Constant.IS_NOT_DEL_INT);
        devMainBase.setCode(generateUniqueCode(devMainBase));
        // 给生产时间和非生产时间设置默认值
        if (devMainBase.getCheckDatePrud() == null) {
            devMainBase.setCheckDatePrud(0);
        }
        if (devMainBase.getCheckDateUprud() == null) {
            devMainBase.setCheckDateUprud(0);
        }
        return devMainBaseDao.save(devMainBase);
    }

    /**
     * generateUniqueCode
     *
     * @param object
     * @return
     */
    @Override
    public String generateUniqueCode(Object object) {
        DevMainBaseEntity devMainBase = (DevMainBaseEntity) object;
        /*
        判断维护项是否为空
            如果不为空，不做任何处理
            如果为空，根据是预测性还是预防性，找到那个最近编码然后继续处理
         */
        String dcode = devMainBase.getCode();
        if (StrUtil.isEmpty(dcode)) {
            Integer mainType = devMainBase.getMainType();
            if (mainType == null) {
                mainType = 2;
            }
            String dcodePrefix = mainType.equals(1) ? "PDM-" : "PM-";
            String lastDCode = devMainBaseDao.getLastDCode(dcodePrefix);
            return com.sugon.modules.utils.StrUtil.increase(lastDCode, dcodePrefix, 4, 1);
        }
        return null;
    }

    /**
     * update
     *
     * @param devMainBase 实体
     * @return
     */
    @Override
    public int update(DevMainBaseEntity devMainBase) {
        devMainBase.setUpdateUser(getUserId());
        devMainBase.setUpdateDate(DateUtil.date());
        // 给生产时间和非生产时间设置默认值
        if (devMainBase.getCheckDatePrud() == null) {
            devMainBase.setCheckDatePrud(0);
        }
        if (devMainBase.getCheckDateUprud() == null) {
            devMainBase.setCheckDateUprud(0);
        }
        return devMainBaseDao.update(devMainBase);
    }

    /**
     * switchStatus
     *
     * @param on
     * @param ids
     */
    @Override
    public void switchStatus(Boolean on, String[] ids) {
        for (String id : ids) {
            DevMainBaseEntity devMainBase = devMainBaseDao.queryObject(id);
            if (on) {
                devMainBase.setLockFlag(1);
            } else {
                devMainBase.setLockFlag(0);
            }
            update(devMainBase);
        }
    }

    /**
     * delete
     *
     * @param id
     * @return
     */
    @Override
    public int delete(String id) {
        return devMainBaseDao.delete(id);
    }

    /**
     * deleteBatch
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(String[] ids) {
        return devMainBaseDao.deleteBatch(ids);
    }

    /**
     * saveMainBaseId
     *
     * @param planId
     * @return
     */
    @Override
    public List<DevMainBaseEntity> saveMainBaseId(String planId) {
        //查询巡检规程关联表信息 查询的是与巡检计划关联的维护规程
//        List<InspectionJoinEntity> joinEntityList = inspectionJoinDao.queryListById(planId);
        /*List<DevMainBaseEntity> devMainBaseEntityList = null;
        List<DevMainBaseEntity> devMainBaseEntityList2 = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < joinEntityList.size(); i++) {
            String id = joinEntityList.get(i).getInspectionRecordingId();
            //查询与维护规程相关的维护选项 即维护库的数据list
            devMainBaseEntityList = devMainBaseDao.getMainBaseId(joinEntityList.get(i).getInspectionRecordingId());
            if (devMainBaseEntityList != null) {
                for (DevMainBaseEntity devMainBaseEntity : devMainBaseEntityList) {
                    //  devMainBaseEntityList2.add(devMainBaseEntity);
                    map.put("patrolPlan", joinEntityList.get(i).getInspectionRecordingId());
                    map.put("createDate", new Date());
                    //查询是否存在 (巡检记录选项关联实体)
                    // List<DevRecordOptionEntity> devRecordList= devRecordOptionDao.queryListByPlan(map);
                    //如果不存在 新增
                    DevRecordOptionEntity devRecordOptionEntity = new DevRecordOptionEntity();
                    devRecordOptionEntity.setId(RandomUtil.randomString(32));
                    devRecordOptionEntity.setCreateDate(new Date());
                    devRecordOptionEntity.setCreateUser(getUserId());
                    devRecordOptionEntity.setDelFlag(Integer.valueOf(Constant.IS_NOT_DEL));
                    devRecordOptionEntity.setId(RandomUtil.randomString(32));
                    devRecordOptionEntity.setPatrolPlan(joinEntityList.get(i).getInspectionPlanId());//巡检计划id
                    devRecordOptionEntity.setMainBaseName(devMainBaseEntity.getName());//维护库选项名称
                    devRecordOptionEntity.setMainBaseId(devMainBaseEntity.getId());//维护库选项名称id
                    devRecordOptionEntity.setStatus(Integer.valueOf(Constant.IS_NORMAL));
                    devRecordOptionDao.save(devRecordOptionEntity);
                }
            }
        }
        return devMainBaseEntityList2;*/
        return new ArrayList<>();
    }

}
